package com.lenovo.tool;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class FileFilter {
	private static FileFilter fileFilter;

	private String[] strings;
	private String[] arrays;

	public static boolean isAdvanced = true;

	private FileFilter() throws IOException {
		if (isAdvanced) {
			Document doc;
			try {
				File file = new File("./filter_translations.xml");
				doc = DocumentUtils.openDocument(file);

				NodeList nodes;
				Element node;
				String value;
				List<String> list = new ArrayList<String>();

				nodes = ((Element)doc.getElementsByTagName("strings").item(0)).getChildNodes();
				for (int i = 0; i < nodes.getLength(); i++) {
					if(nodes.item(i) instanceof Element) {
						node = (Element) nodes.item(i);
						value = node.getTextContent().trim();
						if (value.length() > 0) {
							list.add(value);
						}
					}
				}
				strings = new String[list.size()];
				list.toArray(strings);
				list.clear();

				nodes = ((Element)doc.getElementsByTagName("arrays").item(0)).getElementsByTagName("item");
				for (int i = 0; i < nodes.getLength(); i++) {
					if(nodes.item(i) instanceof Element) {
						node = (Element) nodes.item(i);
						value = node.getTextContent().trim();
						if (value.length() > 0) {
							list.add(value);
						}
					}
				}
				arrays = new String[list.size()];
				list.toArray(arrays);
				list.clear();
				list = null;
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
		} else {
			strings = new String[] { "strings.xml", "mtk-strings.xml" };
			arrays = new String[] { "arrays.xml", "mtk-arrays.xml" };
		}
	}

	public static FileFilter getInstance() throws IOException {
		if (fileFilter == null) {
			fileFilter = new FileFilter();
		}
		return fileFilter;
	}

	public String[] getStringFiles() {
		return strings;
	}

	public String[] getArrayFiles() {
		return arrays;
	}

	public String[] getAllFiles() {
		String[] all = new String[arrays.length + strings.length];
		for (int i = 0; i < strings.length; i++) {
			all[i] = strings[i];
		}
		for (int i = 0; i < arrays.length; i++) {
			all[strings.length + i] = arrays[i];
		}
		return all;
	}
}
